package com.make.house.api.filter;

import com.alibaba.fastjson.JSON;
import com.make.house.api.model.ActionStatus;
import com.make.house.api.model.JSONResult;
import com.make.house.api.utils.AppSignUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;

/**
 * Created by yll on 17/11/18.
 * 全局过滤器
 */
@WebFilter(filterName = "全局过滤器", urlPatterns = "/*")
public class GlobalFilter implements Filter {

    protected static Logger logger= LoggerFactory.getLogger(GlobalFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        logger.info("开始进入接口请求");
        //过滤掉不必要拦截前面的接口
        if(GlobalFilterUtil.filterSpecialUrl(request.getRequestURL().toString())){
            logger.info("特殊的接口直接传递到我们的服务器进行操作--》" + request.getRequestURL().toString());
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        /**校验 app_sign 是否正确*/
        JSONResult response = new JSONResult();
        StringBuilder sb = new StringBuilder();
        HashMap<String, String> paraMap = new HashMap<String, String>();
        //权限校验参数
        String app_sign = "";
        long startTime = System.currentTimeMillis();
        sb.append("\n路径: " + request.getRequestURL() + "\n");
        sb.append("method: " + request.getMethod() + "\n");
        sb.append("QueryString:  " + request.getQueryString() + "\n");
        sb.append("请求参数:\n");
        Enumeration<String> paras = request.getParameterNames();
        while (paras.hasMoreElements()) {
            String name = paras.nextElement();
            String value = request.getParameter(name);
            if (!"app_sign".equals(name)){
                paraMap.put(name, value);
            }else {
                app_sign = value;
            }
            sb.append(name + ":" + value + "\n");
        }
        if (!app_sign.equals(AppSignUtil.getTheAppSign(paraMap))) {
            sb.append("方法耗时: " + (System.currentTimeMillis() - startTime) + "毫秒\n");
            response.setStatus(ActionStatus.PARAMAS_ERROR.inValue());
            response.setDesc("Invalid app_sign");
            response.setData(null);
            sb.append("权限验证失败：" + "传入的app_sign: "+ app_sign +  " 服务器端sign: " + AppSignUtil.getTheAppSign(paraMap));
            logger.error(sb.toString());
            ((HttpServletResponse) servletResponse).setHeader("Content-type", "application/json;charset=UTF-8");
            servletResponse.getOutputStream().write(JSON.toJSONBytes(response));
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
//                //判断返回值是jsonObject还是jsonArray
//                if (responseContent.startsWith("[")) {
//                    response.setData(new JsonParser().parse(responseContent).getAsJsonArray());
//                } else {
//                    response.setData(new JsonParser().parse(responseContent).getAsJsonObject());
//                }
//                response.setStatus(ActionStatus.NORMAL_RETURNED.inValue());
//                response.setDesc(ActionStatus.NORMAL_RETURNED.getDescription());
            sb.append("方法耗时: " + (System.currentTimeMillis() - startTime) + "毫秒\n");
//                sb.append("响应参数: " + responseContent);
            logger.info(sb.toString());
        }

    }

    @Override
    public void destroy() {

    }
}
